package net.tngou.jtdb.sql;


import net.tngou.jtdb.netty.TngouClient;
import net.tngou.jtdb.util.ConfigurationUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class DBManager {
	static ObjectPool<TngouClient> pool = null;
	private static Log log = LogFactory.getLog(DBManager.class);
	private static ConfigurationUtil config = ConfigurationUtil.getInstance();
	public static TngouClient getConnection() {
		 try { 
			 if(pool==null)
			 {
				 _getPool();
			 }
			 return pool.borrowObject();		
			} catch (Exception e) {
				log.error("取得连接失败！");
				pool=null;
			}
		return null;
	}

	public static void closeConnection(TngouClient tngouClient) {
		
		try {		
			 if(pool==null)
			 {
				 _getPool();
			 }
			pool.returnObject(tngouClient);
			log.info("回收连接！");
		} catch (Exception e) {
			log.error("回收连接失败！");
			e.printStackTrace();
		}
		
	}
	
	public static void close(TngouClient tngouClient) {
		if(tngouClient==null) return;
		try {
			tngouClient.close();
			pool.clear();
			pool.close();
			pool=null;
			log.info("关闭连接！");
		} catch (Exception e) {
			log.error("关闭连接失败！");
		}
		
	}


private static  void _getPool() {
	PooledObjectFactory<TngouClient> factory = new DataSourcePoolableObjectFactory();
	GenericObjectPoolConfig poolconfig = new GenericObjectPoolConfig() ; 
	poolconfig.setLifo(false);
	poolconfig.setMaxIdle(config.getMaxidle());
	poolconfig.setMinIdle(config.getMinidle());
	poolconfig.setMaxTotal(config.getMaxtotal());
	poolconfig.setMaxWaitMillis(config.getMaxwaitmillis());
	pool = new GenericObjectPool<TngouClient>(factory, poolconfig); 
	log.info("创建连接池！");
	
}
}
